<template>
  <div class="user-wrapper">
    <Tabs
      @change="handleChangeTab"
      :currentKey="searchParams.type[0]"
      :tabsConfig="dict['user_type']"
      :hasBorder="true"
    />
    <div class="custom-table-list-wrapper">
      <div class="search" :class="{ active: toggleSearchStatus }">
        <div class="search-left" ref="searchFromRef">
          <el-form class="search-form" inline>
            <el-form-item
              label="是否巡检员"
              v-if="searchParams.type[0] !== '5'"
            >
              <el-select
                class="search-select"
                v-model="searchParams.isPatrol"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :label="item.name"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关键词">
              <el-input
                class="search-input"
                v-model="searchParams.keywords"
                placeholder="请输入真实姓名、手机号码"
                :suffix-icon="Search"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <a
            class="search-left-toggle"
            v-if="showToggle"
            @click="handleToggleSearch"
          >
            <svg-icon :name="toggleSearchStatus ? 'up' : 'down'" />
            {{ toggleSearchStatus ? '收起' : '展开' }}
          </a>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="initTableList(1)"
            ><svg-icon name="search" size="14px" />搜索</el-button
          >
          <el-button @click="handleResetCustom"
            ><svg-icon name="reset" size="17px" />重置</el-button
          >
        </div>
      </div>
      <div class="bottom">
        <div class="left" v-if="searchParams.type[0] === '1'">
          <div class="left-title">
            <span v-if="treeType === 'unit'"
              ><el-icon><HomeFilled /></el-icon>企业列表</span
            >
            <span v-else
              ><el-icon @click="handleBackUnit"><DArrowLeft /></el-icon
              >部门列表</span
            >
            <svg-icon name="refresh" size="17px" @click="handleNodeClick({})" />
          </div>
          <div class="left-list">
            <el-tree
              :data="departmentTreeData"
              :props="treeDefaultProps"
              @node-click="handleNodeClick"
              :expand-on-click-node="false"
              :default-expand-all="true"
            />
          </div>
        </div>
        <div class="content">
          <div class="content-operate">
            <span>
              <el-button
                v-if="searchParams.type[0] !== '1'"
                type="primary"
                @click="
                  handleAdd(
                    `新增${getDictValue('user_type', searchParams.type[0])}`,
                    { type: searchParams.type[0] },
                  )
                "
                ><svg-icon name="add" size="15px" />新增人员</el-button
              >
              <!--              <el-button-->
              <!--                type="primary"-->
              <!--                @click="handlePer"-->
              <!--                v-if="searchParams.type[0] !== '5'"-->
              <!--                ><svg-icon name="add" size="15px" />区域范围权限</el-button-->
              <!--              >-->
              <el-button
                v-if="
                  currentUser.getButtonPermissionByCode('user_password_reset')
                "
                type="primary"
                @click="handleResetPassword"
                ><svg-icon name="reset" size="15px" />
                {{
                  currentUser.getButonNameByCode('user_password_reset')
                }}</el-button
              >
            </span>
          </div>
          <div class="content-table">
            <el-table
              ref="tableRef"
              class="custom-table"
              :data="tableData"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" />
              <el-table-column type="index" label="序号" width="60px" />
              <el-table-column prop="userName" label="真实姓名" />
              <el-table-column
                prop="loginName"
                label="手机号码/账号"
                min-width="110"
              >
                <template #default="scope">
                  {{
                    scope.row.loginName.replace(
                      /^(\d{3})(\d{4})(\d{4})$/,
                      '$1****$3',
                    )
                  }}
                </template>
              </el-table-column>
              <template v-if="searchParams.type[0] === '1'">
                <el-table-column
                  prop="oaunit"
                  label="单位"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="deptName"
                  label="部门"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="visitRegionName"
                  label="访问区域"
                  show-overflow-tooltip
                />
                <!-- <el-table-column
                  prop="mainPost"
                  label="岗位"
                  show-overflow-tooltip
                />
                <el-table-column prop="jobLevel" label="职务级别" /> -->
                <el-table-column
                  prop="isPatrol"
                  label="是否巡检人员"
                  min-width="100"
                >
                  <template #default="scope">
                    {{ getDictValue('yn', scope.row.isPatrol) }}
                  </template>
                </el-table-column>
              </template>
              <template
                v-else-if="['2', '3', '4'].includes(searchParams.type[0])"
              >
                <el-table-column prop="unitContent" label="所属单位">
                  <template #default="scope">
                    {{
                      scope.row.unitName ||
                      scope.row.relationUnit ||
                      scope.row.unitContent
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="visitRegionName"
                  label="访问区域"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="mainPost"
                  label="访问有效期"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    {{ moment(scope.row.visitStartTime).format('YYYY-MM-DD') }}
                    -
                    {{ moment(scope.row.visitEndTime).format('YYYY-MM-DD') }}
                  </template>
                </el-table-column>
                <el-table-column prop="isPatrol" label="是否巡检人员">
                  <template #default="scope">
                    {{ getDictValue('yn', scope.row.isPatrol) }}
                  </template>
                </el-table-column>
              </template>
              <el-table-column prop="roleName" label="角色" />
              <el-table-column prop="userState" label="是否启用">
                <template #default="scope">
                  <!-- {{ getDictValue('yn', scope.row.userState) }} -->
                  <el-switch
                    :active-value="1"
                    :inactive-value="0"
                    v-model="scope.row.userState"
                    :before-change="handleChangeStatus.bind(this, scope.row)"
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column prop="createTime" label="创建时间" /> -->
              <el-table-column label="操作" width="160px">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="handleDetail(scope.row)"
                    >详情</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    @click="
                      handleEdit(
                        scope.row,
                        `编辑${getDictValue('user_type', searchParams.type[0])}`,
                      )
                    "
                    v-if="['2', '3', '4', '5'].includes(scope.row.type)"
                    >编辑</el-button
                  >
                  <el-button
                    link
                    type="danger"
                    @click="handleDelete(scope.row)"
                    v-if="['2', '3', '4', '5'].includes(scope.row.type)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="content-page">
            <el-pagination
              class="custom-pagination"
              :current-page="paginationParams.pageIndex"
              :page-size="paginationParams.pageSize"
              background
              :page-sizes="[10, 20, 30, 50]"
              layout="total, prev, pager, next, sizes, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="initTableList"
            />
          </div>
        </div>
      </div>
    </div>
    <AddPatrolUser
      ref="addPatrolUserRef"
      :detail="currentDetail"
      @close="handleClose"
    />
    <AddSystemUser
      ref="addSystemUserRef"
      :detail="currentDetail"
      @close="handleClose"
    />
    <AccessPerDialog ref="accessPerRef" @close="handleClosePer" />
    <DetailDialog
      ref="detailRef"
      :detail="currentDetail"
      @close="handleClose"
    />
    <reset-password-dialog
      ref="resetPasswordDialogRef"
      @close="handleCloseResetPasswordDialog"
    />
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { useTableList } from '@/hooks/useTableList'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DArrowLeft, HomeFilled } from '@element-plus/icons-vue'
import moment from 'moment'
import Tabs from '@/components/tabs/index.vue'
import AddPatrolUser from './addPatrolUser.vue'
import AddSystemUser from './addSystemUser.vue'
import DetailDialog from './detail.vue'
import AccessPerDialog from './components/accessPerDialog.vue'
import { useDict } from '@/hooks/useDict'
import {
  getDepartmentList,
  getUnitList,
  getUserDetail,
  getUserList,
  userAdd,
  userDelete,
} from '@/api/manager/systemManage/user.js'
import ResetPasswordDialog from '@/views/manager/systemManage/user/reserUserPassword.vue'
import { useUserStore } from '@/store/user.js'

const currentUser = useUserStore()

const { dict, getDictValue, getDictStyle } = useDict(['user_type', 'yn'])
const searchParams = ref({
  deptId: '',
  type: ['1'],
})
const {
  Search,
  toggleSearchStatus,
  showToggle,
  handleToggleSearch,
  tableData,
  paginationParams,
  total,
  initTableList,
  handleSizeChange,
  handleReset,
  handleDelete,
  addRef,
  detailRef,
  currentDetail,
  handleDetail,
  handleClose,
  searchFromRef,
} = useTableList(searchParams, getUserList, userDelete)

const resetPasswordDialogRef = ref()

const handleCloseResetPasswordDialog = () => {
  resetPasswordDialogRef.value.dialogVisible = false
}

const handleChangeTab = (val) => {
  multipleSelection.value = []
  searchParams.value.deptId = ''
  searchParams.value.unitId = ''
  searchParams.value.type = [val]
  initTableList(1)
}

const departmentTreeData = ref([])
const treeDefaultProps = ref({
  children: 'children',
  label: 'name',
})

const treeType = ref('unit')
const unitOptions = ref([])
const currentUnitName = ref('')
const initUnitTreeData = async () => {
  const res = await getUnitList()
  if (!res.success) {
    ElMessage.error(res.message)
    return
  }
  unitOptions.value = res.data
  departmentTreeData.value = unitOptions.value
}
const initDepartmentTreeData = async (pkid) => {
  const res = await getDepartmentList({ unitId: pkid })
  if (!res.success) {
    ElMessage.error(res.message)
    return
  }
  departmentTreeData.value = res.data
}
const handleNodeClick = (val) => {
  if (treeType.value === 'unit') {
    searchParams.value.unitId = val.pkid
    searchParams.value.deptId = ''
    if (val.pkid) {
      initDepartmentTreeData(val.pkid)
      treeType.value = 'dept'
      currentUnitName.value = val.name
    }
  } else {
    searchParams.value.deptId = val.pkid
  }
  initTableList(1)
}
const handleBackUnit = () => {
  treeType.value = 'unit'
  searchParams.value.unitId = ''
  searchParams.value.deptId = ''
  departmentTreeData.value = unitOptions.value
  initTableList(1)
}

const addPatrolUserRef = ref()
const addSystemUserRef = ref()
const handleAdd = (title, row) => {
  currentDetail.value = { ...row }
  if (row.type === '5') {
    addSystemUserRef.value.dialogVisible = true
    addSystemUserRef.value.title = title
  } else {
    addPatrolUserRef.value.dialogVisible = true
    addPatrolUserRef.value.title = title
  }
}

const handleResetPassword = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先勾选人员')
    return
  }
  const pkid = multipleSelection.value
    .map((i) => {
      return i.pkid
    })
    .toString()
  resetPasswordDialogRef.value.setFormPkid(pkid)
  resetPasswordDialogRef.value.dialogVisible = true
}

const handleEdit = (row, title) => {
  if (row.type === '5') {
    addSystemUserRef.value.dialogVisible = true
    addSystemUserRef.value.title = title
  } else {
    addPatrolUserRef.value.dialogVisible = true
    addPatrolUserRef.value.title = title
  }
  currentDetail.value = { ...row }
}
const handleChangeStatus = async (row) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm(`是否切换启用状态`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const detailRes = await getUserDetail({ pkid: row.pkid })
        const params = {
          userInfoAo: {
            ...detailRes.data.userInfo,
            userState: detailRes.data.userInfo.userState === 1 ? 0 : 1,
          },
          coreUserMetaInfo: detailRes.data.coreUserMetaInfo,
        }
        const res = await userAdd(params)
        if (res.success) {
          ElMessage.success('切换成功')
          resolve(true)
          initTableList()
        } else {
          ElMessage.error(res.message)
          resolve(false)
        }
      })
      .catch(() => {
        resolve(false)
      })
  })
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const accessPerRef = ref()
const handlePer = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先勾选人员')
    return
  }
  accessPerRef.value.userIds = multipleSelection.value.map((i) => {
    return i.pkid
  })
  accessPerRef.value.dialogVisible = true
}
const tableRef = ref()
const handleClosePer = (isFlash) => {
  if (isFlash) {
    multipleSelection.value = []
    initTableList(1)
    tableRef.value.clearSelection()
  }
}

const handleResetCustom = () => {
  const params = {
    deptId: searchParams.value.deptId,
    type: searchParams.value.type,
    unitId: searchParams.value.unitId,
  }
  handleReset(params)
}
onMounted(() => {
  initUnitTreeData()
  initTableList(1)
})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/table.scss';
.user-wrapper {
  width: 100%;
  height: 100%;

  .custom-table-list-wrapper {
    width: 100%;
    height: calc(100% - 50px);
    display: flex;
    flex-direction: column;
    .search {
      border-radius: 0;
    }
    .bottom {
      width: 100%;
      height: calc(100% - 100px);
      // flex: 1;
      display: flex;
      .left {
        width: 350px;
        height: 100%;
        box-sizing: border-box;
        // border-right: 1px solid #d5deed;
        background-color: #fff;
        box-shadow: 0px 0px 10px 0px rgba(72, 121, 238, 0.1);
        border-radius: 4px 0 0 4px;
        margin-right: 20px;
        // padding: 20px;
        &-title {
          width: 100%;
          height: 50px;
          box-sizing: border-box;
          border-bottom: 1px solid #d5deed;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 15px 0 20px;
          span {
            font-size: 16px;
            font-weight: 500;
            color: #000000;
            display: flex;
            align-items: center;
          }
          .el-icon {
            color: #409eff;
            font-size: 18px;
            margin-right: 5px;
            cursor: pointer;
          }
          .svg-icon {
            cursor: pointer;
          }
        }
        &-list {
          width: 100%;
          height: calc(100% - 50px);
          overflow-y: auto;
          box-sizing: border-box;
          padding: 20px;
        }
      }
      .content {
        height: 100%;
        flex: 1;
      }
    }
  }
}
</style>
